package com.jerry.boot.core.web;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
@Slf4j
public class JFilterChain {

    private List<JFilter> filters;

    public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
        boolean res = true;
        if (CollUtil.isNotEmpty(filters)) {
            for (JFilter filter : filters) {
                if (log.isDebugEnabled()) {
                    log.debug("url:{}, JFilter {} start to deal", request.getServletPath(), filter.getClass().getName());
                }
                boolean doNext = filter.deal(request, response);
                if (log.isDebugEnabled()) {
                    log.debug("url:{} JFilter {} finish to deal, result={}", request.getServletPath(), filter.getClass().getName(), doNext);
                }
                if (!doNext) {
                    res = false;
                    break;
                }
            }
        }
        return res;
    }


    public void setFilters(List<JFilter> filters) {
        this.filters = filters;
    }

    public void addFilter(JFilter filter) {
        this.filters.add(filter);
    }

    public void addFilter(JFilter filter, int index) {
        this.filters.add(index, filter);
    }
}
